import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
// 通过 channel 的方式保存 h5 页面的登录状态
const String htmlStr = '''
<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="utf-8" />
  <title>通过URL向flutter传递参数</title>
</head>
<body>
  <button id="btn" style="font-size: 2.5em">获取登录信息</button>
  <div id="resultTxt" style="font-size: 2.5em">这里展示flutter传递过来的数据</button>
  <script type="text/javascript">
    var btn = document.getElementById("btn");
    btn.addEventListener('click', function(){
      // 通过注册的 getLoginInfo channel 向 flutter 发送消息
      getLoginInfo.postMessage("cc");
    }, false)
    function hiCallJs(msg){
      document.getElementById('resultTxt').innerHTML = 'Flutter传递过来的登录信息：' + msg;
    }
  </script>
</body>
</html>
''';
class FlutterH5AuthChannel extends StatefulWidget {
  const FlutterH5AuthChannel({super.key});

  @override
  State<FlutterH5AuthChannel> createState() => _FlutterH5AuthChannelState();
}

class _FlutterH5AuthChannelState extends State<FlutterH5AuthChannel> {
  late WebViewController controller;

  get _loadBtn => FilledButton(onPressed: (){
    controller.loadHtmlString(htmlStr);
  }, child: const Text('加载H5页面',style: const TextStyle(color: Colors.white),));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: const Text('channel保存登录状态',style: const TextStyle(color: Colors.white)),
          actions: [_loadBtn],
      ),
      body: WebViewWidget(controller: controller),

    );
  }
  @override
  void initState() {
    super.initState();
    controller = WebViewController()
    ..setJavaScriptMode(JavaScriptMode.unrestricted)
    ..addJavaScriptChannel('getLoginInfo', onMessageReceived: (JavaScriptMessage message){
      // 将登录信息传递给H5页面并保存，保证时候的http请求是登录状态
      var info = {'token':'token111','uid':'1001'};
      var infoString = json.encode(info);
      controller.runJavaScript("hiCallJs('$infoString')");
    })
    ;
  }
}
